import { asyncRoutes, constantRoutes } from '@/router'

const state = {
  routes: constantRoutes,
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    // const homeRouter = constantRoutes.find(v => v.path === '/')
    // console.log(state.routes, 'homeRouter')
    // homeRouter.children.push(...routes)
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    // state.routes = constantRoutes
  }
}

const actions = {
  generateRoutes({ commit }, permissionList) {
    return new Promise(resolve => {
      const accessedRoutes = []
      // console.log(asyncRoutes)
      // console.log(permissionList)
      /**
       * 权限判断
       */
      asyncRoutes.forEach(asyncItem => {
        // 不使用权限判断
        // accessedRoutes.push(asyncItem)

        permissionList.forEach(permissionItem => {
          if (asyncItem.meta) {
            /**
             * 判断一级权限
             */
            if (asyncItem.path === permissionItem.url) {
              const childrenRowList = []
              for (const asyncChildrenIndex in asyncItem.children) {
                const asyncChildrenItem = asyncItem.children[asyncChildrenIndex]
                permissionItem.children.forEach(permissionItemChildren => {
                  /**
                   * 判断二级权限
                   */
                  if (asyncChildrenItem.path === permissionItemChildren.url) {
                    /**
                     * 判断三级权限
                     */
                    // if (typeof asyncChildrenItem.children !== 'undefined' && asyncChildrenItem.children.length !== 0) {
                    //   asyncItem.children[asyncChildrenIndex].children = asyncChildrenItem.children.filter(asyncChildrenLastChildrenRow => {
                    //     let hasLastChildren = false
                    //     if (typeof permissionItemChildren.children !== 'undefined' && permissionItemChildren.children.length !== 0) {
                    //       permissionItemChildren.children.forEach(permissionItemLastItemChildren => {
                    //         if (asyncChildrenLastChildrenRow.path.includes(permissionItemLastItemChildren.url)) {
                    //           hasLastChildren = true
                    //         }
                    //       })
                    //     }
                    //     return hasLastChildren
                    //   })
                    // }
                    childrenRowList.push(asyncItem.children[asyncChildrenIndex])
                  }
                })
              }
              asyncItem.children = childrenRowList
              accessedRoutes.push(asyncItem)
            }
          }
        })
      })
      // console.log('accessedRoutes：', accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
